<template>
  <el-dialog
    v-el-drag-dialog="{updataFull, updataDialogWidth}"
    :fullscreen="isfullscreen"
    :width="dialogWidth"
    :visible="visible"
    :title="dialogTitle"
    :append-to-body="true"
    @open="open"
    @close="close"
  >
    <el-form
      ref="saveForm"
      :model="formData"
      label-width="auto"
      :rules="rules"
      class="pl-20 pr-20"
    >
      <div class="flex">
        <el-form-item :label="$t('MIGRATION_NAME') + ':'" prop="planName" class="w-50 flex-1">
          <el-input v-if="operateType === 'add'" v-model.trim="formData.planName" maxlength="32" />
          <template v-else>
            {{ planData.planName }}
          </template>
        </el-form-item>
        <el-form-item
          v-if="operateType === 'result'"
          :label="$t('EXECUTE_RESULT') + ':'"
          class="w-50 font-weight-bolder"
        >
          {{ $t('MIGRATION_STATUS_' + planData.status) }}
        </el-form-item>
      </div>
      <el-form-item v-if="planData && planData.bizOpen" :label="$t('SERVICE_NAME') + ':'">
        {{ planData.bizOpen.bizName }}
      </el-form-item>
      <el-form-item
        :label="$t('A_END_STATION') + '/' + $t('FEATURE_TYPE_NODE') + '/' + $t('PORT') + ':'"
      >
        {{
          getStationName(planData.startNode) +
            (planData.startPort ? '/' + planData.startPort.bizName : '')
        }}
      </el-form-item>
      <el-form-item
        :label="$t('Z_END_STATION') + '/' + $t('FEATURE_TYPE_NODE') + '/' + $t('PORT') + ':'"
      >
        {{
          getStationName(planData.endNode) +
            (planData.endPort ? '/' + planData.endPort.bizName : '')
        }}
      </el-form-item>
      <div class="flex">
        <!-- 迁移计划 -->
        <el-form-item
          v-if="
            operateType === 'add' ||
              operateType === 'result' ||
              operateType === 'view' ||
              operateType === 'manual'
          "
          class="w-50 flex-1"
          :label="planListName"
        >
          <template v-for="(item, index) in planData.executePlanList">
            <div
              v-if="!listType || item.migrationOperation === listType"
              :key="index"
              class="plan-info"
            >
              {{ getLink(item) }}
            </div>
          </template>
        </el-form-item>
        <!-- 回退计划 -->
        <el-form-item
          v-if="
            (operateType === 'result' && planData.status === 'ROLLBACK_SUCCESS') ||
              operateType === 'rollback' ||
              operateType === 'rollbackManual' ||
              operateType === 'viewRollback'
          "
          class="w-50 flex-1"
          :label="rollbackPlanListName"
        >
          <template v-for="(item, index) in planData.rollbackPlanList">
            <div
              v-if="!listType || item.migrationOperation === listType"
              :key="index"
              class="plan-info"
            >
              {{ getLink(item) }}
            </div>
          </template>
        </el-form-item>
      </div>
      <el-form-item
        v-if="
          operateType === 'add' ||
            (operateType === 'view' && planData.status === 'MIGRATION_READER')
        "
        label-width="0"
        prop="planExecuteTime"
      >
        <el-checkbox v-model="formData.noewExecute" :disabled="operateType !== 'add'">{{
          $t('EXECUTE_METHOD_NOW')
        }}</el-checkbox>
        <el-date-picker
          v-if="!formData.noewExecute"
          v-model="formData.planExecuteTime"
          :disabled="operateType !== 'add'"
          value-format="yyyy-MM-dd HH:mm:ss"
          class="ml-20"
          style="width: 300px"
          type="datetime"
          placeholder=""
          default-time="12:00:00"
        />
      </el-form-item>
      <el-form-item label-width="0">
        <b>{{ noticeWord }}</b>
      </el-form-item>
    </el-form>
    <!-- 结果topo -->
    <detail-topo v-if="operateType === 'result'" :render-data="renderData" />
    <template v-slot:footer>
      <el-button @click="close">{{ $t('CLOSE') }}</el-button>
      <!-- 人工操作完成按钮 -->
      <el-button
        v-if="
          (operateType === 'manual' || operateType === 'rollbackManual') && listType === 'MANUAL'
        "
        @click="$debounce(manualOperate)"
      >{{ $t('CONFIRM') }}</el-button>
      <!-- 回退按钮 -->
      <el-button v-if="operateType === 'rollback'" @click="$debounce(rollback)">{{
        $t('CONFIRM')
      }}</el-button>
      <!-- 新增提交按钮 -->
      <el-button v-if="operateType === 'add'" @click="$debounce(save)">{{
        $t('CONFIRM')
      }}</el-button>
      <!-- 导出链路迁移 -->
      <el-button
        v-if="permission.export &&
          ((operateType === 'result' && planData.status !== 'ROLLBACK_SUCCESS') ||
            operateType === 'view')
        "
        @click="$debounce(handleExport, 'migrate')"
      >{{ $t('EXPORT') }}</el-button>
      <!-- 导出链路回滚 -->
      <el-button
        v-if="
          permission.export &&
            ((operateType === 'result' && planData.status === 'ROLLBACK_SUCCESS') ||
              operateType === 'rollback' ||
              operateType === 'viewRollback')
        "
        @click="$debounce(handleExport, 'rollback')"
      >{{ $t('EXPORT') }}</el-button>
    </template>
  </el-dialog>
</template>
<script>
  import { mapGetters } from 'vuex'
  import linkMigration from '@/api/oen/LinkMigrationApi'
  import exportApi from '@/api/oen/ExportApi'
  import { downloadFile } from '@/utils/common'
  import DetailTopo from './DetailTopo'

  export default {
    components: {
      DetailTopo
    },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      planData: {
        type: Object,
        default: () => {
          return {}
        }
      },
      operateType: {
        type: String,
        default: 'add'
      },
      title: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        dialogWidth: '600px',
        formData: {
          planName: '',
          noewExecute: false,
          planExecuteTime: ''
        },
        renderData: [],
        listType: null,
        dialogTitle: '',
        noticeWord: ''
      }
    },
    computed: {
      ...mapGetters(['baseRegionList']),
      permission() {
        return this.$store.getters.getAuthData('link:cutover')
      },
      planListName() {
        return (
          (!this.listType
            ? this.$t('MIGRATION_PLAN')
            : this.listType === 'MANUAL'
              ? this.$t('MANUAL_OPERATION')
              : this.$t('AUTOMATIC_OPERATION')) + ':'
        )
      },
      rollbackPlanListName() {
        return (
          (!this.listType
            ? this.$t('ROLLBACK_PLAN')
            : this.listType === 'MANUAL'
              ? this.$t('MANUAL_OPERATION')
              : this.$t('AUTOMATIC_OPERATION')) + ':'
        )
      },
      rules() {
        return {
          planName: [
            {
              required: true,
              message: this.$t('PLEASE_INPUT') + this.$t('MIGRATION_NAME'),
              trigger: 'blur'
            }
          ],
          planExecuteTime: [
            {
              required: !this.formData.noewExecute,
              message: this.$t('PLEASE_SELECT') + this.$t('EXECUTION_TIME'),
              trigger: 'blur'
            }
          ]
        }
      }
    },
    methods: {
      getLink(data) {
        console.log('getLink', data)
        let str = ''
        // 移纤
        if (data.migrationPlanType === 'FIBER_MOVE') {
          str = this.$t('MIGRATE_PORT_CONNECT', {
            msg1: data.cutover.deviceName,
            msg2: data.cutover.port.bizName,
            msg3: data.cutover.connPort.bizName
          })
        }
        // 新增网段
        if (data.migrationPlanType === 'ADD_NOTWORK') {
          const segmentData = data.networkSegment
          str = segmentData.segmentChannelList
            .map(i => {
              return this.$t('MIGRATE_CONNECT_LINK', {
                msg1: this.getStationName(segmentData.startNode),
                msg2: i.startPort.bizName,
                msg3: this.getStationName(segmentData.endNode),
                msg4: i.endPort.bizName
              })
            })
            .join('；')
          // data.networkSegment
        }
        // 删除网段通道
        if (data.migrationPlanType === 'DEL_NOTWORK_CHANNEL') {
          str = this.$t('MIGRATE_BREAK_LINK', {
            msg1: this.getStationName(data.sourceNode),
            msg2: data.sourcePort.bizName,
            msg3: this.getStationName(data.targetNode),
            msg4: data.targetPort.bizName
          })
        }
        const needManual = data.migrationOperation === 'MANUAL' ? this.$t('NEED_MANUAL') : ''
        return this.$utils.handleServiceI18n(str + needManual)
      },
      getStationName(nodeData) {
        if (!nodeData) return ''
        const stationData = this.baseRegionList.find(i => i.regionId === nodeData.stationId)
        return (stationData ? stationData.regionName + '/' : '') + nodeData.nodeName
      },
      save() {
        this.$refs.saveForm.validate(valid => {
          if (valid) {
            this.$emit('save', this.formData)
          }
        })
      },
      open() {
        this.dialogTitle = this.title
        this.noticeWord = ''
        console.log('operateType', this.operateType)
        this.listType = null
        this.dialogWidth = '600px'
        this.formData = this.operateType !== 'add' ? this.planData : this.$options.data().formData
        if (this.operateType === 'manual' || this.operateType === 'rollbackManual') {
          this.listType = 'MANUAL'
          this.noticeWord = this.$t('MANUAL_PART_COMPLETED')
        }
        if (this.operateType === 'view' || this.operateType === 'rollback') {
          this.noticeWord = this.$t('MANUAL_WORK_FIRST')
          if (this.planData.status === 'MIGRATION_RUNNING') {
            this.noticeWord = this.$t('FIBER_SHIFTING_IMPLEMENTED')
          }
        }
        if (this.operateType === 'viewRollback') {
          this.noticeWord = this.$t('ROLLBACK_PERFORMED')
        }
        // 查看结果显示topo
        if (this.operateType === 'result') {
          this.dialogWidth = '1200px'
          const renderData =
            this.planData.status === 'MIGRATION_SUCCESS'
              ? this.planData.finalLayout
              : this.planData.initTopo
          this.renderData = JSON.parse(renderData || '{}')
        }
      },
      manualOperate() {
        linkMigration.manualComplete({ planId: this.planData.planId }).then(res => {
          this.$message.success(this.$t('OPERATE_SUCCESS'))
          this.listType = 'AUTO'
          this.noticeWord = this.$t('EXECUTION_TIME_AUTO')
          this.dialogTitle = this.$t('AUTO_REMOVAL_OPERATION')
          this.$emit('reload')
        })
      },
      rollback() {
        linkMigration.rollback({ planId: this.planData.planId }).then(res => {
          this.$message.success(this.$t('OPERATE_SUCCESS'))
          this.$emit('reload')
          this.close()
        })
      },
      handleExport(key) {
        if (key === 'migrate') {
          exportApi.linkMigrationExecute({ planId: this.planData.planId }).then(res => {
            downloadFile(res, this.$t('MIGRATION_PLAN'))
          })
        } else {
          exportApi.linkMigrationRollback({ planId: this.planData.planId }).then(res => {
            downloadFile(res, this.$t('ROLLBACK_PLAN'))
          })
        }
      },
      close() {
        this.$emit('close')
      }
    }
  }
</script>
<style>
  .plan-info {
    margin-top: 7px;
    line-height: 1.2;
  }
</style>
